<template>
  <header class="app-header">
    <div class="header-left">
      <div class="logo" />
      <span class="system-title">电商后台管理系统</span>
    </div>
    <div class="header-search">
      <el-select v-model="searchType" placeholder="搜索类型" size="large" style="width: 140px;">
        <el-option v-for="item in searchTypes" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-input 
        v-model="searchKeyword" 
        placeholder="请输入搜索内容" 
        size="large"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button :icon="Search" @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
    </div>
    <div class="header-right">
      <!-- 系统通知 -->
      <div class="notification-wrapper" ref="notificationRef">
        <el-tooltip content="系统通知" placement="bottom">
          <div class="notification-icon" @click="showNotificationDropdown = !showNotificationDropdown">
            <el-icon class="header-icon"><BellFilled /></el-icon>
            <el-badge v-if="totalUnreadCount > 0" :value="totalUnreadCount" class="notification-badge" />
          </div>
        </el-tooltip>
        
        <!-- 通知下拉面板 -->
        <transition name="dropdown-fade">
          <div v-if="showNotificationDropdown" class="notification-dropdown" @click.stop>
            <div class="notification-header">
              <span class="notification-title">系统通知</span>
              <el-button size="small" type="primary" text @click="markAllAsRead">全部已读</el-button>
            </div>
            
            <!-- 通知类型Tab -->
            <el-tabs v-model="activeNotificationTab" class="notification-tabs">
              <el-tab-pane label="公告信息" name="announcement">
                <div class="notification-list">
                  <div 
                    v-for="item in announcementList" 
                    :key="item.id" 
                    class="notification-item"
                    :class="{ unread: !item.isRead }"
                    @click="viewNotificationDetail(item, 'announcement')"
                  >
                    <div class="notification-icon-wrapper">
                      <el-icon class="notification-type-icon" :class="item.type">
                        <InfoFilled v-if="item.type === 'info'" />
                        <Warning v-else-if="item.type === 'warning'" />
                        <SuccessFilled v-else-if="item.type === 'success'" />
                        <CircleCloseFilled v-else />
                      </el-icon>
                    </div>
                    <div class="notification-content">
                      <div class="notification-title-text">{{ item.title }}</div>
                      <div class="notification-desc">{{ item.content }}</div>
                      <div class="notification-time">{{ item.time }}</div>
                    </div>
                    <div v-if="!item.isRead" class="unread-dot"></div>
                  </div>
                  <div v-if="announcementList.length === 0" class="empty-notification">
                    暂无公告信息
                  </div>
                </div>
              </el-tab-pane>
              
              <el-tab-pane label="系统异常" name="system">
                <div class="notification-list">
                  <div 
                    v-for="item in systemErrorList" 
                    :key="item.id" 
                    class="notification-item"
                    :class="{ unread: !item.isRead }"
                    @click="viewNotificationDetail(item, 'system')"
                  >
                    <div class="notification-icon-wrapper">
                      <el-icon class="notification-type-icon error">
                        <CircleCloseFilled />
                      </el-icon>
                    </div>
                    <div class="notification-content">
                      <div class="notification-title-text">{{ item.title }}</div>
                      <div class="notification-desc">{{ item.content }}</div>
                      <div class="notification-time">{{ item.time }}</div>
                    </div>
                    <div v-if="!item.isRead" class="unread-dot"></div>
                  </div>
                  <div v-if="systemErrorList.length === 0" class="empty-notification">
                    暂无系统异常信息
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
            
            <div class="notification-footer">
              <el-button size="small" type="primary" text @click="viewAllNotifications">查看全部</el-button>
            </div>
          </div>
        </transition>
      </div>
      
      <div class="user-info" @click="showDropdown = !showDropdown" ref="userRef">
        <el-avatar :src="user?.avatar" size="small" />
        <span class="welcome">欢迎您，{{ userName }}</span>
        <el-icon><ArrowDown /></el-icon>
        <transition name="dropdown-fade">
          <div v-if="showDropdown" class="user-dropdown" @click.stop>
            <div class="dropdown-item" @click="goProfile">个人信息</div>
            <el-divider style="margin: 8px 0" />
            <div class="dropdown-item logout" @click="onLogout">退出登录</div>
          </div>
        </transition>
      </div>
      
      <!-- 通知详情弹窗 -->
      <el-dialog
        v-model="notificationDetailDialog.visible"
        title="通知详情"
        width="600px"
        :close-on-click-modal="false"
      >
        <div v-if="notificationDetailDialog.data" class="notification-detail">
          <div class="detail-header">
            <h3 class="detail-title">{{ notificationDetailDialog.data.title }}</h3>
            <div class="detail-meta">
              <span class="detail-time">{{ notificationDetailDialog.data.time }}</span>
              <el-tag :type="getPriorityType(notificationDetailDialog.data.type)" size="small" class="detail-priority">
                {{ getPriorityText(notificationDetailDialog.data.type) }}
              </el-tag>
            </div>
          </div>
          
          <div class="detail-content">
            <div class="content-section">
              <h4 class="section-title">通知内容：</h4>
              <p class="content-text">{{ notificationDetailDialog.data.content }}</p>
            </div>
            
            <div v-if="notificationDetailDialog.data.details && notificationDetailDialog.data.details.length > 0" class="content-section">
              <h4 class="section-title">详细信息：</h4>
              <ul class="detail-list">
                <li v-for="(detail, index) in notificationDetailDialog.data.details" :key="index">
                  {{ detail }}
                </li>
              </ul>
            </div>
            
            <div v-if="notificationDetailDialog.data.affectedFunctions && notificationDetailDialog.data.affectedFunctions.length > 0" class="content-section">
              <h4 class="section-title">可能影响的功能：</h4>
              <ul class="detail-list">
                <li v-for="(func, index) in notificationDetailDialog.data.affectedFunctions" :key="index">
                  {{ func }}
                </li>
              </ul>
            </div>
            
            <div v-if="notificationDetailDialog.data.remark" class="content-section">
              <h4 class="section-title">备注：</h4>
              <p class="content-text">{{ notificationDetailDialog.data.remark }}</p>
            </div>
          </div>
        </div>
        <template #footer>
          <el-button @click="notificationDetailDialog.visible = false">关闭</el-button>
          <el-button type="primary" @click="markAsReadFromDetail">标记已读</el-button>
        </template>
      </el-dialog>
    </div>
  </header>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { useAuthStore } from '@/store/auth'
import { useNotificationStore, type NotificationItem } from '@/store/notification'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { BellFilled, ArrowDown, Search, InfoFilled, Warning, SuccessFilled, CircleCloseFilled } from '@element-plus/icons-vue'

const auth = useAuthStore()
const notificationStore = useNotificationStore()
const router = useRouter()
const showDropdown = ref(false)
const userRef = ref<HTMLElement | null>(null)

// 通知相关
const showNotificationDropdown = ref(false)
const notificationRef = ref<HTMLElement | null>(null)
const activeNotificationTab = ref('announcement')

// 通知详情弹窗
const notificationDetailDialog = reactive({
  visible: false,
  data: null as NotificationItem | null
})

// 从store获取通知数据
const announcementList = computed(() => notificationStore.announcementList)
const systemErrorList = computed(() => notificationStore.systemErrorList)
const totalUnreadCount = computed(() => notificationStore.totalUnreadCount)

// 搜索相关
const searchType = ref('member')
const searchKeyword = ref('')
const searchTypes = [
  { label: '会员ID', value: 'member' },
  { label: '商品ID', value: 'product' },
  { label: '打包同捆ID(箱号)', value: 'package' },
  { label: '快递入库单号', value: 'express' },
  { label: '订单号ID', value: 'order' },
  { label: '账单ID', value: 'bill' },
  { label: '交易平台', value: 'platform' },
  { label: '国际单号', value: 'international' }
]

const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索内容')
    return
  }
  
  const keyword = searchKeyword.value.trim()
  
  // 根据不同的搜索类型跳转到不同的页面
  switch (searchType.value) {
    case 'member':
      router.push(`/member/list?id=${keyword}`)
      break
    case 'product':
      router.push(`/product/detail?id=${keyword}`)
      break
    case 'package':
      router.push(`/warehouse/package?id=${keyword}`)
      break
    case 'express':
      router.push(`/warehouse/express?number=${keyword}`)
      break
    case 'order':
      router.push(`/order/detail?id=${keyword}`)
      break
    case 'bill':
      router.push(`/finance/bill?id=${keyword}`)
      break
    case 'platform':
      router.push(`/platform/detail?name=${keyword}`)
      break
    case 'international':
      router.push(`/order/international?number=${keyword}`)
      break
    default:
      ElMessage.warning('未知的搜索类型')
  }
  
  // 搜索后清空搜索框
  searchKeyword.value = ''
}

const user = computed(() => auth.user)
const userName = computed(() => user.value?.name || '')

function onLogout() {
  auth.logout()
  ElMessage.success('已退出登录')
  router.push('/login')
}

// 通知相关方法
function markAsRead(id: string, type: 'announcement' | 'system') {
  notificationStore.markAsRead(id, type)
}

function markAllAsRead() {
  notificationStore.markAllAsRead()
  ElMessage.success('已全部标记为已读')
}

function viewAllNotifications() {
  showNotificationDropdown.value = false
  router.push('/notification')
}

function viewNotificationDetail(item: NotificationItem, type: 'announcement' | 'system') {
  notificationDetailDialog.data = item
  notificationDetailDialog.visible = true
  showNotificationDropdown.value = false
}

function markAsReadFromDetail() {
  if (notificationDetailDialog.data) {
    // 确定通知类型
    const isAnnouncement = announcementList.value.some(item => item.id === notificationDetailDialog.data!.id)
    const type = isAnnouncement ? 'announcement' : 'system'
    
    notificationStore.markAsRead(notificationDetailDialog.data.id, type)
    ElMessage.success('已标记为已读')
    notificationDetailDialog.visible = false
  }
}

function getPriorityType(type: string) {
  const typeMap: Record<string, string> = {
    info: '',
    warning: 'warning',
    success: 'success',
    error: 'danger'
  }
  return typeMap[type] || ''
}

function getPriorityText(type: string) {
  const typeMap: Record<string, string> = {
    info: '普通',
    warning: '重要',
    success: '成功',
    error: '紧急'
  }
  return typeMap[type] || '普通'
}

function handleNotificationClickOutside(e: MouseEvent) {
  if (notificationRef.value && !notificationRef.value.contains(e.target as Node)) {
    showNotificationDropdown.value = false
  }
}

function goProfile() {
  showDropdown.value = false
  router.push('/profile')
}

function handleClickOutside(e: MouseEvent) {
  if (userRef.value && !userRef.value.contains(e.target as Node)) {
    showDropdown.value = false
  }
  handleNotificationClickOutside(e)
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})
onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.app-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: var(--header-height);
  background: var(--header-bg);
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.04);
  padding: 0 32px;
  z-index: 100;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}
.header-left {
  display: flex;
  align-items: center;
}
.header-search {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 500px;
}
.logo {
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #409eff 0%, #764ba2 100%);
  border-radius: 8px;
  margin-right: 16px;
}
.system-title {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}
.header-right {
  display: flex;
  align-items: center;
  gap: 24px;
}

/* 通知相关样式 */
.notification-wrapper {
  position: relative;
}

.notification-icon {
  position: relative;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.notification-icon:hover {
  background-color: #f5f7fa;
}

.notification-badge {
  position: absolute;
  top: 2px;
  right: 2px;
  transform: scale(0.8);
}

.notification-badge :deep(.el-badge__content) {
  height: 16px;
  min-width: 16px;
  line-height: 16px;
  font-size: 10px;
  padding: 0 4px;
}

.notification-dropdown {
  position: absolute;
  right: 0;
  top: 44px;
  width: 400px;
  background: #fff;
  box-shadow: 0 4px 16px 0 rgba(0,0,0,0.12);
  border-radius: 8px;
  z-index: 200;
  animation: dropdown-in 0.2s;
  max-height: 500px;
  overflow: hidden;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.notification-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.notification-tabs {
  padding: 0 20px;
}

.notification-tabs :deep(.el-tabs__header) {
  margin-bottom: 12px;
}

.notification-tabs :deep(.el-tabs__nav-wrap) {
  padding: 0;
}

.notification-tabs :deep(.el-tabs__item) {
  font-size: 14px;
  padding: 0 16px;
}

.notification-list {
  max-height: 300px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  position: relative;
  transition: background-color 0.2s;
}

.notification-item:hover {
  background-color: #f8f9fa;
}

.notification-item.unread {
  background-color: #f0f9ff;
}

.notification-item.unread:hover {
  background-color: #e0f2fe;
}

.notification-icon-wrapper {
  margin-right: 12px;
  margin-top: 2px;
}

.notification-type-icon {
  font-size: 16px;
  padding: 6px;
  border-radius: 4px;
}

.notification-type-icon.info {
  color: #409eff;
  background-color: #ecf5ff;
}

.notification-type-icon.warning {
  color: #e6a23c;
  background-color: #fdf6ec;
}

.notification-type-icon.success {
  color: #67c23a;
  background-color: #f0f9ff;
}

.notification-type-icon.error {
  color: #f56c6c;
  background-color: #fef0f0;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-title-text {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  line-height: 1.4;
}

.notification-desc {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
  margin-bottom: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.notification-time {
  font-size: 11px;
  color: #909399;
}

.unread-dot {
  position: absolute;
  top: 12px;
  right: 0;
  width: 8px;
  height: 8px;
  background-color: #f56c6c;
  border-radius: 50%;
}

.empty-notification {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
  font-size: 14px;
}

.notification-footer {
  padding: 12px 20px;
  border-top: 1px solid #f0f0f0;
  text-align: center;
}

/* 通知详情样式 */
.notification-detail {
  padding: 0;
}

.detail-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-title {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.detail-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.detail-time {
  font-size: 14px;
  color: #909399;
}

.detail-priority {
  font-size: 12px;
}

.detail-content {
  padding: 0;
}

.content-section {
  margin-bottom: 20px;
}

.content-section:last-child {
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.content-text {
  margin: 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.detail-list {
  margin: 0;
  padding-left: 20px;
}

.detail-list li {
  margin-bottom: 6px;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

.detail-list li:last-child {
  margin-bottom: 0;
}
.header-icon {
  font-size: 22px;
  color: #909399;
  cursor: pointer;
}
.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  position: relative;
  gap: 8px;
  user-select: none;
}
.welcome {
  font-size: 15px;
  color: #303133;
  margin: 0 4px;
}
.user-dropdown {
  position: absolute;
  right: 0;
  top: 44px;
  width: 160px;
  background: #fff;
  box-shadow: 0 4px 16px 0 rgba(0,0,0,0.12);
  border-radius: 8px;
  padding: 8px 0;
  z-index: 200;
  animation: dropdown-in 0.2s;
}
.dropdown-item {
  padding: 10px 20px;
  font-size: 15px;
  color: #303133;
  cursor: pointer;
  transition: background 0.2s;
}
.dropdown-item:hover {
  background: #f5f7fa;
}
.logout {
  color: #f56c6c;
}
@keyframes dropdown-in {
  0% { opacity: 0; transform: translateY(-10px); }
  100% { opacity: 1; transform: translateY(0); }
}
.dropdown-fade-enter-active, .dropdown-fade-leave-active {
  transition: opacity 0.2s, transform 0.2s;
}
.dropdown-fade-enter-from, .dropdown-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>